package com.example.library.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.library.common.PageResult;
import com.example.library.common.Result;
import com.example.library.dto.LoginRequest;
import com.example.library.dto.RegisterRequest;
import com.example.library.dto.UserQueryRequest;
import com.example.library.entity.User;
import com.example.library.service.UserService;
import com.example.library.utils.JwtUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户控制器
 *
   */
@Slf4j
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;
    private final JwtUtils jwtUtils;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@Valid @RequestBody LoginRequest loginRequest) {
        String token = userService.login(loginRequest);
        
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("tokenType", "Bearer");
        
        return Result.success("登录成功", data);
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<User> register(@Valid @RequestBody RegisterRequest registerRequest) {
        User user = userService.register(registerRequest);
        return Result.success("注册成功", user);
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/current")
    public Result<User> getCurrentUser(HttpServletRequest request) {
        String token = jwtUtils.getTokenFromRequest(request);
        Long userId = jwtUtils.getUserIdFromToken(token);
        User user = userService.getById(userId);
        
        // 不返回密码
        user.setPassword(null);
        return Result.success(user);
    }

    /**
     * 分页查询用户列表
     */
    @GetMapping
    public PageResult<User> getUserPage(UserQueryRequest queryRequest) {
        IPage<User> page = userService.getUserPage(queryRequest);
        return PageResult.success(page);
    }

    /**
     * 根据ID获取用户信息
     */
    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable Long id) {
        User user = userService.getById(id);
        if (user != null) {
            // 不返回密码
            user.setPassword(null);
        }
        return Result.success(user);
    }

    /**
     * 创建用户
     */
    @PostMapping
    public Result<Void> createUser(@Valid @RequestBody User user) {
        boolean success = userService.createUser(user);
        return success ? Result.success("用户创建成功") : Result.error("用户创建失败");
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/{id}")
    public Result<Void> updateUser(@PathVariable Long id, @Valid @RequestBody User user) {
        user.setId(id);
        boolean success = userService.updateUser(user);
        return success ? Result.success("用户更新成功") : Result.error("用户更新失败");
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteUser(@PathVariable Long id) {
        boolean success = userService.deleteUser(id);
        return success ? Result.success("用户删除成功") : Result.error("用户删除失败");
    }

    /**
     * 批量删除用户
     */
    @DeleteMapping("/batch")
    public Result<Void> batchDeleteUsers(@RequestBody List<Long> userIds) {
        boolean success = userService.batchDeleteUsers(userIds);
        return success ? Result.success("批量删除成功") : Result.error("批量删除失败");
    }

    /**
     * 更新用户状态
     */
    @PutMapping("/{id}/status")
    public Result<Void> updateUserStatus(@PathVariable Long id) {
        boolean success = userService.updateUserStatus(id);
        return success ? Result.success("状态更新成功") : Result.error("状态更新失败");
    }

    /**
     * 批量更新用户状态
     */
    @PutMapping("/batch/status")
    public Result<Void> batchUpdateUserStatus(@RequestBody List<Long> userIds, @RequestParam Integer status) {
        boolean success = userService.batchUpdateUserStatus(userIds, status);
        return success ? Result.success("批量状态更新成功") : Result.error("批量状态更新失败");
    }

    /**
     * 重置用户密码
     */
    @PutMapping("/{id}/password/reset")
    public Result<Void> resetPassword(@PathVariable Long id, @RequestParam String newPassword) {
        boolean success = userService.resetPassword(id, newPassword);
        return success ? Result.success("密码重置成功") : Result.error("密码重置失败");
    }

    /**
     * 修改密码
     */
    @PutMapping("/password/change")
    public Result<Void> changePassword(HttpServletRequest request,
                                       @RequestParam String oldPassword,
                                       @RequestParam String newPassword) {
        String token = jwtUtils.getTokenFromRequest(request);
        Long userId = jwtUtils.getUserIdFromToken(token);
        
        boolean success = userService.changePassword(userId, oldPassword, newPassword);
        return success ? Result.success("密码修改成功") : Result.error("密码修改失败");
    }

    /**
     * 更新头像
     */
    @PutMapping("/avatar")
    public Result<Void> updateAvatar(HttpServletRequest request, @RequestParam String avatar) {
        String token = jwtUtils.getTokenFromRequest(request);
        Long userId = jwtUtils.getUserIdFromToken(token);
        
        boolean success = userService.updateAvatar(userId, avatar);
        return success ? Result.success("头像更新成功") : Result.error("头像更新失败");
    }

    /**
     * 获取用户统计信息
     */
    @GetMapping("/statistics")
    public Result<Object> getUserStatistics() {
        Object statistics = userService.getUserStatistics();
        return Result.success(statistics);
    }

    /**
     * 检查用户名是否存在
     */
    @GetMapping("/check/username")
    public Result<Boolean> checkUsername(@RequestParam String username) {
        boolean exists = userService.existsByUsername(username);
        return Result.success(exists);
    }

    /**
     * 检查邮箱是否存在
     */
    @GetMapping("/check/email")
    public Result<Boolean> checkEmail(@RequestParam String email) {
        boolean exists = userService.existsByEmail(email);
        return Result.success(exists);
    }

    /**
     * 检查手机号是否存在
     */
    @GetMapping("/check/phone")
    public Result<Boolean> checkPhone(@RequestParam String phone) {
        boolean exists = userService.existsByPhone(phone);
        return Result.success(exists);
    }

}